import React, { useState, useEffect } from "react";
import { useSelector } from 'react-redux';
import { CRow, CTable, CTableBody, CTableDataCell, CTableHead, CTableHeaderCell, CTableRow, CPagination, CPaginationItem } from '@coreui/react';

const DoctorSchedule = () => {
    const [message, setMessage] = useState('');
    const [scheduleName, setScheduleName] = useState([]);
    const [doctorsInfo, setDoctorsInfo ] = useState([]);
    const [tableSchedule, setTableSchedule] = useState([]);
    const [params, setParams] = useState({
      schedule_name: 'schedule',
      doctors_name: null,
      limit: 15,
      offset: 0,
      });
    const token = useSelector((state) => state.token);
    const fullname = useSelector((state) => state.fullname);
  
    const nextPage = () => {
      setParams(prevParams => ({
      ...prevParams,
        offset: prevParams.offset + params.limit,
      }));
      fetchData();
    };
  
  
    const previousPage = () => {
      if (params.offset > 0) {
        setParams(prevParams => ({
        ...prevParams,
          offset: prevParams.offset - params.limit,
        }));
        fetchData();
      }
    };
  
  
    const fetchScheduleName = async () => {
      try {
          const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/schedule_name`,
            {
              method: 'GET',
              headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${token}`
              },
            }
          );
          const data = await response.json();
          setScheduleName(data);
      } catch (error) {
          console.error('Ошибка при получении данных:', error);
      }
      };
    
    const fetchData = async () => {
        let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/doctors_schedule?doctors_name=${fullname}`;
        if (params.schedule_name) {
          url += `&schedule_name=${params.schedule_name}`;
        }
        if (params.limit) {
          url += `&limit=${params.limit}`;
        }
        if (params.offset) {
          url += `&offset=${params.offset}`;
        }
        try {
          const response = await fetch(url,
            {
              method: 'GET',
              headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${token}`
              },
            }
          );
          const data = await response.json();
          setTableSchedule(data);
        } catch (error) {
          console.error('Ошибка при получении данных:', error);
        }
      };
  
    useEffect(() => {
        fetchScheduleName()
        fetchData();
        }, [params]);
  
    const columns = [
      { key: 'id', _style: { width: '5%' }, label: '#' },
      { key: 'date', _style: { width: '20%' }, label: 'Дата' },
      { key: 'shift', _style: { width: '30%' }, label: 'Смена' },
      { key: 'week', _style: { width: '15%' }, label: 'Неделя' },
      { key: 'weekday', _style: { width: '15%' }, label: 'День недели' },
      { key: 'name', _style: { width: '30%' }, label: 'ФИО' },    
      { key: 'modality', _style: { width: '20%' }, label: 'Модальность' },
    ];
  
    return (
      <>
      <h1>Посмотреть расписание</h1>
      <br></br>
      <CRow>
        <CTable striped>
          <CTableHead>
            <CTableRow>
              {columns.map((column, index) => (
                <CTableHeaderCell key={index} scope="col">{column.label}</CTableHeaderCell>
              ))}
            </CTableRow>
          </CTableHead>
          <CTableBody>
            {tableSchedule.map((item, index) => (
              <CTableRow key={index}>
                <CTableHeaderCell scope="row">{item.id}</CTableHeaderCell>
                <CTableDataCell>{item.date}</CTableDataCell>
                <CTableDataCell>{item.shift}</CTableDataCell>
                <CTableDataCell>{item.week}</CTableDataCell>
                <CTableDataCell>{item.weekday}</CTableDataCell>
                <CTableDataCell>{item.name}</CTableDataCell>
                <CTableDataCell>{item.modality}</CTableDataCell>
              </CTableRow>
            ))}
          </CTableBody>
        </CTable>
      </CRow>
        <CPagination align="end" aria-label="Page navigation example">
        <CPaginationItem onClick={previousPage}>Previous</CPaginationItem>
        <CPaginationItem onClick={nextPage}>Next</CPaginationItem>
      </CPagination>
    </>

    );
};

export default DoctorSchedule;
